#include "batteryicon.h"

#include <QIcon>
#include <QtDBus>
#include <QDebug>
#include <QStyleOption>
#include <QPainter>
#include <QPainterPath>

#define ORG_UKUI_STYLE "org.ukui.style"
#define STYLE_NAME "styleName"
#define SYSTEM_FONT_SIZE "systemFontSize"

BatteryIcon::BatteryIcon(QWidget *parent) : QPushButton(parent)
{
    this->setFixedSize(QSize(48, 48));
    this->setIconSize(QSize(30, 30));
    this->setStyle(new CustomStyle);

    m_iface = new QDBusInterface("org.ukui.upower", "/upower/BatteryInfo", "org.ukui.upower.battery", QDBusConnection::sessionBus());
    QDBusConnection::sessionBus().connect(
        "org.ukui.upower", "/upower/BatteryInfo", "org.ukui.upower.battery", "BatteryIcon", this, SLOT(iconChange(QString)));
    QDBusReply<QString> reply = m_iface->call("IconName");
    this->setIcon(QIcon::fromTheme(reply.value()));
    this->setProperty("useIconHighlightEffect", 0x10);
    this->setFlat(true);
}

void BatteryIcon::iconChange(QString str)
{
    qDebug() << "BatteryIcon::iconChang";
    if (!str.isNull()) {
        QIcon icon = QIcon::fromTheme(str);
        this->setIcon(icon);
        //        this->setProperty("useIconHighlightEffect", 0x10);
        //      this->setProperty("isWindowButton", 0x1);
        //    this->setFlat(true);
    }
}

void BatteryIcon::gsettingWacther()
{
    const QByteArray styleId(ORG_UKUI_STYLE);
    if (QGSettings::isSchemaInstalled(styleId)) {
        QGSettings *styleSettings = new QGSettings(styleId);
        connect(styleSettings, &QGSettings::changed, this, [=](const QString &key) {
            if (key == STYLE_NAME) {
                QDBusReply<QString> reply = m_iface->call("IconName");
                iconChange(reply.value());
            }
        });
    }
}

// void BatteryIcon::paintEvent(QPaintEvent *ev)
//{
//    QStyleOption opt;
//    opt.init(this);
//    QPainter p(this);
//    double transparence = transparency * 255;
//    QColor color = palette().color(QPalette::Base);
//    color.setAlpha(100);
//    QBrush brush = QBrush(QColor(0,0,0,0));
//    p.setBrush(brush);
//    p.setBrush(this->palette().base());
//    p.setBrush(QBrush(QColor(19, 19, 20, 0)));
//    p.setPen(Qt::NoPen);
//    QPainterPath path;
//    opt.rect.adjust(0,0,0,0);
//    path.addRoundedRect(opt.rect,0,0);
//    p.setRenderHint(QPainter::Antialiasing);  // 反锯齿;
//    p.drawRoundedRect(opt.rect,0,0);
//    setProperty("blurRegion",QRegion(path.toFillPolygon().toPolygon()));
//    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
//}
